<?php
/**
 * Created by PhpStorm.
 * User: z-benjamin
 * Date: 16/8/31
 * Time: 下午8:58
 */

namespace wxml\models\product;

use yii;
use common\libs\Pagination;
use common\libs\RemoteHttp;
use common\libs\CommonModel;
use wxml\models\product\AR\ProductAR;

class Product extends CommonModel {

    public $statusMap = ['ON_SHELF' => 'ON_SHELF', 'UNDER_SHELF' => 'UNDER_SHELF', 'DELETED' => 'DELETED'];

    public function fetchProduct($isbn) {
        $url = 'http://search.m.dangdang.com/search_ajax.php';
        $result = RemoteHttp::get($url, ['have_ad'=>0,'keyword' => $isbn, 'act' => 'get_product_flow_search',]);
        return $result;
    }

    public function createProduct($product,$user) {

        $isNew = isset($product['id']) && !empty($product['id']);
        if($isNew) {
            $productAr = ProductAR::findOne(['id' => $product['id']]);
            if($productAr->user_id!==$user->id){
                $this->setError(-1,'不能编辑其他人的书籍');
                return false;
            }
        } else {
            $productAr = new ProductAR();
        }
        $dbTrans = Yii::$app->db->beginTransaction();
        try {
            $productAr->user_id = $user->id;
            $productAr->title = $product['title'];
            $productAr->images = json_encode($product['images'], true);
            $productAr->content = $product['content'];
            $productAr->author = $product['author'];
            $productAr->publisher = $product['publisher'];
            $productAr->isbn = $product['isbn'];
            $productAr->original_price = $product['original_price'];
            $productAr->sale_price = $product['sale_price'];
            $productAr->depreciation_rate = $product['depreciation_rate'];
            $productAr->create_time = time();
            $productAr->status = $this->statusMap['ON_SHELF'];
            $res = $productAr->save();
            if(!$res) {
                throw new \Exception("保存书籍失败");
            }
            $dbTrans->commit();
        } catch(\Exception $e) {
            $dbTrans->rollback();
            $this->errMsg = $e->getMessage();
            return false;
        }
        return true;
    }

    public function getProductList($filters = array(), $orders = array(), $offset = 0, $limit = 20) {
        $query = ProductAR::find();
        if($filters) {
            foreach($filters as $filter) {
                $query->andWhere($filter);
            }
        }
        $fields=[
            'title','images','sale_price','original_price','id'
        ];
        $count = $query->count();
        // create a pagination object with the total count
        $pagination = new Pagination(['totalCount' => $count, 'perPage' => $limit, 'limit' => $limit, 'offset' => $offset]);
        // limit the query using the pagination and retrieve the articles
        $products = $query->select($fields)->offset($pagination->offset)->limit($pagination->limit)->orderBy($orders)->all();
        return array('list' => $products, 'pages' => $pagination);

    }

    public function getProductDetail($product_id){
        $product=ProductAR::findOne(['id'=>$product_id]);
        return $product->toArray();
    }
}
